#!/bin/bash -e

# Temporal script to deploy application to AWS infra.
APP_NAME=dqa-web-front
APP_ARTIFACT=${APP_NAME}.tar.gz
DEPLOYMENT_ARTIFACT=${APP_NAME}-latest.zip
# S3_URL=${S3_STG_TARGET_URL:=s3://dqa-stg-packages}

error_check()
{
#       ----------------------------------------------------------------
#       Function for exit due to fatal program error
#               Accepts 1 argument:
#                       string containing descriptive error message
#       ----------------------------------------------------------------
  if [ $? -ne "0" ];then
    echo "${1:-"Unknown Error"}" 1>&2
    exit 1
  fi
}

echo "PWD: ${PWD}"

# Build application
yarn build:api
error_check "Line $LINENO: fail to build application."


# Compress application archive
if [ -e ${APP_ARTIFACT} ];then
  rm ./${APP_ARTIFACT}
fi
tar -czvf ./${APP_ARTIFACT} \
  package.json \
  .next \
  public \
  dist \
  node_modules \
  next.config.js
error_check "Line $LINENO: fail to compress archive."

# cp -r deployment/ansible/ work_dir
# cp deployment/application_start_stg.sh work_dir/application_start.sh
# cp deployment/appspec.yml work_dir/appspec.yml
# cp deployment/before_install.sh work_dir/before_install.sh
# cp deployment/verify_service.sh work_dir/verify_service.sh

# # Compress deployment archive
# if [ -e ${DEPLOYMENT_ARTIFACT} ]; then
#   rm ${DEPLOYMENT_ARTIFACT}
# fi
# cd work_dir
# zip -r ../${DEPLOYMENT_ARTIFACT} .
# # Upload deployment archive to S3
# cd ..
# if [ -e work_dir ];then
#   rm -rf ./work_dir
# fi
# # aws s3 cp ${DEPLOYMENT_ARTIFACT} ${S3_URL}/${DEPLOYMENT_ARTIFACT}